<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useTypeStore } from '@/stores/index.js'
import {
  useTypeDetailService,
  useAddTypeService,
  useUpdateTypeService
} from '@/api/request.js'

const title = ref('')
// 弹框标记变量
const dialogVisible = ref(false)

// 暴露方法给父组件，通过传递的row判断是删除还是增加
const open = async (row) => {
  title.value = row.id ? '编辑分类' : '增加分类'
  if (row.id) {
    const { data } = await useTypeDetailService(row.id)
    formData.value = data
  }
  dialogVisible.value = true
}
defineExpose({
  open
})

// 表单实例
const form = ref()

// 表单数据绑定对象
const formData = ref({
  id: '',
  cate_name: '',
  cate_alias: ''
})

// 表单自定义校验规则
const rules = {
  cate_name: [
    {
      required: true,
      message: '分类名不能为空',
      trigger: 'blur'
    }
  ],
  cate_alias: [
    {
      required: true,
      message: '分类别名不能为空',
      trigger: 'blur'
    },
    {
      pattern: /^[a-zA-Z0-9]{2,5}$/,
      message: '分类别名应为2-5位的字母或数字组合',
      trigger: 'change'
    }
  ]
}
// 点击确定的回调
const ok = async () => {
  // 校验表单
  await form.value.validate()

  // 如果外界传递了分类数据对应的id  修改操作
  if (formData.value.id) {
    await useUpdateTypeService(formData.value)
  } else {
    // 增加操作
    await useAddTypeService(formData.value)
  }

  // 弹框隐藏 显示修改信息
  dialogVisible.value = false
  ElMessage({
    message: title.value === '编辑分类' ? '编辑成功' : '增加成功',
    type: 'success'
  })
  clearFormData()

  await useTypeStore().getTypeList()
}

// 点击取消的回调
const cancel = () => {
  dialogVisible.value = false
  clearFormData()
}

const clearFormData = () => {
  console.log(formData.value['cate_name'])
  formData.value = {
    id: '',
    cate_name: '',
    cate_alias: ''
  }
}
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" @close="cancel" width="500">
    <div class="main">
      <el-form
        label-width="auto"
        :model="formData"
        :rules="rules"
        ref="form"
        style="max-width: 600px"
      >
        <el-form-item prop="cate_name" label="分类名称：">
          <el-input v-model="formData.cate_name" />
        </el-form-item>
        <el-form-item prop="cate_alias" label="分类别名：">
          <el-input v-model="formData.cate_alias" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="ok"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
